package service

import (
	"fmt"
	logging "github.com/sirupsen/logrus"
	"net/http"
	"webdemo/src/gin/base"
	"webdemo/src/gin/dbconfig"
	"webdemo/src/gin/model"
	"webdemo/src/gin/model/dto"
)

type UserService struct{}

func (service *UserService) Register(user *model.User) *base.Response {
	var count int64

	db := dbconfig.DB
	db.Model(&model.User{}).Where("name=?", user.Name).First(user).Count(&count)
	logging.Info("[UserService][Register] user is ", user)
	var b = 0
	var a = 1 / b
	fmt.Println(a)
	if count > 0 {
		return base.FailedResponse(http.StatusBadRequest, "用户已存在")
	}

	// 创建用户
	// 开启事务
	tx := db.Begin()
	err := tx.Create(&user).Error
	if err != nil {
		logging.Error(err)
		tx.Rollback()
		return base.FailedResponse(http.StatusInternalServerError, err.Error())
	}
	tx.Commit()
	return base.SuccessResponse(true)
}

// 默认有事务
func (service *UserService) Insert(user *model.User) *base.Response {
	result := dbconfig.DB.Create(user)
	if result.Error != nil {
		return base.FailedResponseWithoutCode(result.Error.Error())
	}
	return base.SuccessResponse(user)
}

func (service *UserService) BatchInsert(users *[]model.User) *base.Response {

	result := dbconfig.DB.CreateInBatches(users, 1000)
	if result.Error != nil {
		return base.FailedResponseWithoutCode(result.Error.Error())
	}
	affected := result.RowsAffected
	return base.SuccessResponse(affected)
}

func (service *UserService) QueryUserById(id string) *base.Response {
	user := &model.User{}
	dbconfig.DB.First(user, id)
	// 如果主键是字符串（例如像 uuid）
	// db.First(&user, "id = ?", "1b74413f-f3b8-409f-ac47-e8c062e3472a")
	return base.SuccessResponse(user)
}

func (service *UserService) QueryUserList(userDTO *dto.UserDTO) *base.Response {
	users := &[]model.User{}
	dbconfig.DB.Where("name in ? AND create_time BETWEEN ? AND ?",
		userDTO.NameList, userDTO.StartTime, userDTO.EndTime).Find(users)
	return base.SuccessResponse(users)
}

func (service *UserService) QueryAllUser() *base.Response {
	users := &[]model.User{}
	dbconfig.DB.Find(users)
	return base.SuccessResponse(users)
}

func (service *UserService) Update(user *model.User) *base.Response {
	// Save 会保存所有的字段，即使字段是零值
	//result := dbconfig.DB.Save(user)
	// 使用 Struct 进行 Select（会 select 零值的字段）==更新指定字段
	result := dbconfig.DB.Model(&user).Select("Name", "Age").Updates(user)
	// 根据 `struct` 更新属性，只会更新非零值的字段
	//result := dbconfig.DB.Model(user).Updates(user)
	if result.Error != nil {
		return base.FailedResponseWithoutCode(result.Error.Error())
	}
	return base.SuccessResponse(result.RowsAffected)
}

func (service *UserService) BatchUpdate(user *model.User) *base.Response {
	result := dbconfig.DB.Model(model.User{}).Where("id in ?", []int{1439904092171239426, 201}).Updates(user)
	if result.Error != nil {
		return base.FailedResponseWithoutCode(result.Error.Error())
	}
	return base.SuccessResponse(result.RowsAffected)
}

func (service *UserService) Delete(user *model.User) *base.Response {
	// 根据id删除
	result := dbconfig.DB.Delete(&model.User{}, user.Id)
	// 根据其他条件删除
	//result := dbconfig.DB.Where("name = ?",user.Name).Delete(&model.User{})

	if result.Error != nil {
		return base.FailedResponseWithoutCode(result.Error.Error())
	}
	return base.SuccessResponse(result.RowsAffected)
}

func (service *UserService) ExeSql(user *model.User) *base.Response {
	dbconfig.DB.Raw("SELECT id, name, age FROM users WHERE name = ?", user.Name).Scan(user)

	/*var age int
	dbconfig.DB.Raw("SELECT SUM(age) FROM user").Scan(&age)
	*/
	//dbconfig.DB.Exec("UPDATE orders SET shipped_at = ? WHERE id IN ?", time.Now(), []int64{1, 2, 3})
	return base.SuccessResponse(user)

}
